package com.gupaoedu.chat.server;

import com.gupaoedu.chat.protocol.IMDecoder;
import com.gupaoedu.chat.protocol.IMEncoder;
import com.gupaoedu.chat.server.handler.HttpHandler;
import com.gupaoedu.chat.server.handler.ScoketHandler;
import com.gupaoedu.chat.server.handler.WebSocktHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * Created by ASUS on 2017/10/21.
 */
public class ChatServer {

    /**
     * 进行启动
     */
    public void start(){
        //boss线程
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        //工作线程
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        //启动
        ServerBootstrap b=new ServerBootstrap();
        try {
            b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).
                    option(ChannelOption.SO_BACKLOG,1024)//设置最大线程数
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        public void initChannel(SocketChannel channel) throws Exception {
                            //获取客户端的通道 串行无锁化
                            //解析自定义的协议
//                            channel.pipeline().addLast(new IMDecoder());
//                            channel.pipeline().addLast(new IMEncoder());
//
//                            //增加Socket请求
//                            channel.pipeline().addLast(new ScoketHandler());

                            /** 解析WebSocket请求 */
//                            channel.pipeline().addLast(new WebSocketServerProtocolHandler("/im"));
//                            channel.pipeline().addLast(new WebSocktHandler());

                            //增加 http协议的编码和解码
                            channel.pipeline().addLast(new HttpServerCodec());
                            channel.pipeline().addLast(new HttpObjectAggregator(60*1024));
                            channel.pipeline().addLast(new HttpHandler());
                        }
                    });
            //绑定端口
            ChannelFuture channelFuture=b.bind(8080).sync();
            System.out.println("端口号 80 开始启动.....");
            //关闭任务 不能使用close方法
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //workgroup 关闭
            workerGroup.shutdownGracefully();
            //bossGroup 关闭
            bossGroup.shutdownGracefully();
        }
    }
    /**
     *
     * @param args
     */
    public static void main(String args[]) {
        new ChatServer().start();
    }
}
